import { install } from "./install";
import { createMatcher } from "./create-matcher";
import BrowserHistory from "./history/browserHistory";
import HashHistory from "./history/hashHistory";


class VueRouter {
    constructor(options) {
        let routes = options.routes || []
        // 将路由组成映射表 

        this.beforeEachHooks = []

        this.matcher = createMatcher(routes)
        let mode = options.mode || 'hash'


        if (mode === 'hash') {
            this.history = new HashHistory(this)
        } else {
            this.history = new BrowserHistory(this)
        }

    }

    match(location) {
        return this.matcher.match(location)
    }

    push(location) {
        return this.history.push(location)
    }

    init(app) { //根据路径的变化匹配对应的组件进行渲染，更新视图--- 响应式
        let history = this.history
        history.transitionTo(history.getCurrentLocation(), () => {
            history.setupListener()
        })
        history.listen(newRoute => {
            app._route = newRoute
        })
    }

    beforeEach(cb) { // 会有多个
        this.beforeEachHooks.push(cb)
    }


}



VueRouter.install = install

export default VueRouter
